#!/bin/bash

help() {
  echo "Usage:"
  echo "  zmicro plugin add <plugin_name> <plugin_url> [plugin_version]"
  echo ""
}

core() {
  if [[ $# -eq 0 ]]; then
    help
    exit 0
  fi

  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2
    case $key in
    -h | --help)
      help
      shift # past key
      exit 0
      ;;
    *)
      # echo "ERROR: unknown parameter \"$key\""
      # help
      # exit 1
      break
      ;;
    esac
  done

  local plugin_name=$1
  local plugin_url=$2
  local plugin_version=${3:-master}
  local plugin_path=$(plugin::get_path $plugin_name)

  # @TODO latest => master
  if [ "$plugin_version" ]; then
    plugin_version=master
  fi

  if [ "$plugin_name" = "" ] || [ "$plugin_url" = "" ]; then
    log::error "[$(timestamp)][plugin] plugin name and url is required"
    exit 1
  fi

  log::info "[$(timestamp)][plugin] add $(color::green $plugin_name) version: $plugin_version"

  if [ "$(plugin::exist $plugin_name)" = "true" ]; then
    log::success "[$(timestamp)][plugin] iinstalled before (1): ${plugin_name}"
    exit 0
  fi

  log::debug "[$(timestamp)][plugin] add $plugin_name($plugin_version) ..."
  git clone $plugin_url -b $plugin_version $plugin_path >>$ZMICRO_LOG_COMMON_PATH 2>>$ZMICRO_LOG_ERROR_PATH # 2>&1
  if [ "$?" != "0" ]; then
    log::error "[$(timestamp)][plugin] install error $plugin_name($plugin_version) ..."
    tail -n 50 $ZMICRO_LOG_ERROR_PATH
    exit 1
  fi

  # install depdendencies
  require::plugin_mod $plugin_name

  # register bin
  plugin::register $plugin_name

  log::success "[$(timestamp)][plugin] install success $plugin_name($plugin_version)"
}

run() {
  core $@
}

run $@
